package com.framework.foundation.weixin;

import java.util.HashMap;
import java.util.Map;

import com.framework.foundation.weixin.api.WifiApi;
import com.framework.foundation.weixin.wxdevice.Wxdevice;
import com.framework.foundation.weixin.wxmac.Wxmac;
import com.framework.foundation.weixin.wxmac.WxmacService;
import com.framework.foundation.weixin.wxstore.Wxstore;
import com.framework.foundation.weixin.wxstore.WxstoreService;
import com.framework.foundation.weixin.wxuser.Wxuser;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InWifiConnectedEvent;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.jfinal.weixin.sdk.utils.HttpUtils;
import com.jfinal.weixin.sdk.utils.JsonUtils;

public class WeixinController extends MsgControllerAdapter {

	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可
	 * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
	 */
	@Override
	public ApiConfig getApiConfig() {
		// 根据id获取apiconfig信息
		Wxuser wxuser = Wxuser.me.findById(getPara("id"));
		if (wxuser != null) {
			ApiConfig ac = new ApiConfig();

			// 配置微信 API 相关常量
			ac.setToken(wxuser.getStr("token"));
			ac.setAppId(wxuser.getStr("appid"));
			ac.setAppSecret(wxuser.getStr("appsecret"));

			/**
			 * 是否对消息进行加密，对应于微信平台的消息加解密方式：
			 * 1：true进行加密且必须配置 encodingAesKey
			 * 2：false采用明文模式，同时也支持混合模式
			 */
			ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
			ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
			return ac;
		}
		return null;
	}

	/**
	 * 腾讯地图坐标搜索页面
	 * 
	 * @Author: Brin
	 * @Date: 2016年3月13日 上午9:56:57
	 */
	public void getPoint() {
		render("getPoint.html");
	}

	public void getDeviceList() {
		setApiConfig();
		ApiResult result = WifiApi.getDeviceList(1, 4600894);
		renderJson(result.getJson());
	}

	/**
	 * 获取门店信息
	 * 
	 * @Author: Brin
	 * @Date: 2016年3月11日 下午2:41:39
	 */
	public void test() {
		setApiConfig();
		// renderJson(WifiApi.getStoreList(17).getJson());
		// renderJson(WifiApi.getAllStoreList());
		// renderJson(WifiApi.getAllWifiStoreList());
		// renderJson(WifiApi.getAllDeviceInfo(4600013));

		// for (int i = 0; i < 210; i++) {
		// Wxdevice device = new Wxdevice();
		// device.set("ssid", "WX_JZZ_" + i);
		// device.set("password", "WX123456");
		// device.set("shop_id", 4600013);
		// WifiApi.addDevice(device);
		// // WxdeviceService.me.save(device);
		// }
		// renderNull();

		// 获取门店wifi信息
		// renderJson(WifiApi.getWifiInfo(4601624).getJson());
		renderText("测试");
	}

	/**
	 * 获取wifi门店信息
	 * 
	 * @Author: Brin
	 * @Date: 2016年3月11日 下午2:41:39
	 */
	public void getWifiStoreList() {
		setApiConfig();
		String sid = getPara("sid");
		Map map = WxstoreService.me.findShopId(Integer.parseInt(sid), 1);

		renderJson(JsonUtils.toJson(map));
	}

	public void getQrcode() {
		setApiConfig();
		String url = "https://api.weixin.qq.com/bizwifi/qrcode/get?access_token=" + AccessTokenApi.getAccessTokenStr();

		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("shop_id", 4646486);
		dataMap.put("img_id", 1);
		dataMap.put("ssid", "大润发宜昌店");
		ApiResult result = new ApiResult(HttpUtils.post(url, JsonUtils.toJson(dataMap)));
		renderNull();
	}

	private void setApiConfig() {
		Wxuser wxuser = Wxuser.me.findById(3);
		ApiConfig ac = new ApiConfig();

		// 配置微信 API 相关常量
		ac.setToken(wxuser.getStr("token"));
		ac.setAppId(wxuser.getStr("appid"));
		ac.setAppSecret(wxuser.getStr("appsecret"));

		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式：
		 * 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		ApiConfigKit.setThreadLocalApiConfig(ac);
	}

	@Override
	protected void processInFollowEvent(InFollowEvent inFollowEvent) {
		System.out.println(getPara("id"));

	}

	@Override
	protected void processInWifiConnectedEvent(InWifiConnectedEvent inWifiConnectedEvent) {
		// 提现返回消息以免重复发送
		renderNull();
		// 保存mac地址
		Wxstore store = Wxstore.me.findFirst("SELECT id FROM ww_store WHERE shop_id = ?",
				inWifiConnectedEvent.getShopId());
		if (store != null) {
			// 一个mac地址只能对应一个门店 如果该mac地址存在则进行修改
			Wxmac wxmac = Wxmac.me.findFirst("SELECT * FROM ww_mac WHERE address = ?",
					inWifiConnectedEvent.getDeviceNo());
			if (wxmac == null) {
				wxmac = new Wxmac();
			}
			wxmac.set("address", inWifiConnectedEvent.getDeviceNo());
			wxmac.set("shop_id", Integer.parseInt(inWifiConnectedEvent.getShopId()));
			wxmac.set("store_id", store.getInt("id"));
			wxmac.set("wxuser_id", getParaToInt("id"));
			Wxdevice device = WxmacService.me.getDeviceByMac(wxmac);
			if (device != null) {
				wxmac.set("device_id", device.getInt("id"));
			}
			if (wxmac.get("id") != null) {
				WxmacService.me.update(wxmac);
			} else {
				WxmacService.me.save(wxmac);
			}

		}

	}

	@Override
	protected void processInTextMsg(InTextMsg inTextMsg) {
		System.out.println(getParaMap());
		System.out.println(getPara("id"));
		// 转发给多客服PC客户端
		OutTextMsg outTextMsg = new OutTextMsg(inTextMsg);
		outTextMsg.setContent("你好啊");
		render(outTextMsg);
	}

	@Override
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {
		// TODO Auto-generated method stub

	}

}
